package com.ruoyi.web.controller.office;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.FlashMap;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.support.RequestContextUtils;

import com.ruoyi.biz.domain.diskfile.FileUploadDTO;
import com.ruoyi.biz.service.diskfile.IFileItemStoreService;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.CxSelect;
import com.ruoyi.framework.interceptor.anno.MyPermissions;
import com.ruoyi.office.bean.bo.ChopInfoBO;
import com.ruoyi.office.bean.vo.dto.ChopInfoDTO;
import com.ruoyi.office.bean.vo.qo.ChopInfoQO;
import com.ruoyi.office.domain.ChopInfo;
import com.ruoyi.office.domain.ChopType;
import com.ruoyi.office.service.IChopInfoRefuseService;
import com.ruoyi.office.service.IChopTypeService;
import com.ruoyi.web.controller.biz.data.IdName;
import com.ruoyi.web.controller.core.impl.BaseBQCtrollerExImpls;
import com.ruoyi.web.controller.office.data.ChopStatus;
import com.ruoyi.web.controller.office.data.SealTypes;

/**
 * 信息
 * 
 * @author riverbo
 */
@MyPermissions("用章退回信息")
@Controller
@RequestMapping("office/chopinfo/refuse")
public class ChopInfoRefuseController
		extends BaseBQCtrollerExImpls<IChopInfoRefuseService, ChopInfo, ChopInfoBO, ChopInfoQO, ChopInfoDTO> {
	
	@Autowired
    private HttpServletRequest request;
	
//	@Autowired
//    private HttpServletResponse response;

	@Autowired
	private IChopTypeService chopTypeService;
	
	@Autowired
	private IFileItemStoreService storeService;

	@Override
	public String query(ModelMap mmap) throws Exception {
		mmap.put("canAdd", true);
		mmap.put("canEdit", true);
		mmap.put("canCheck", false);
		List<CxSelect> lsChopType = getChopTypeData();
		mmap.put("ctData", lsChopType);
		//
		List<IdName> sealTypes = SealTypes.getList();
		mmap.put("sealTypes", sealTypes);
		//
		List<IdName> chopStatus = ChopStatus.getList();
		mmap.put("chopStatus", chopStatus);
		mmap.put("curStatus", "3");
		return super.query(mmap);
	}

	@Override
	public String add(ModelMap mmap) throws Exception {
		List<CxSelect> lsChopType = getChopTypeData();
		mmap.put("ctData", lsChopType);
		//
		List<IdName> sealTypes = SealTypes.getList();
		mmap.put("sealTypes", sealTypes);
		//
		List<IdName> chopStatus = ChopStatus.getList();
		mmap.put("chopStatus", chopStatus);
		//
		ChopInfoBO vo = new ChopInfoBO();
		vo.setCaseNo("");
		vo.setCopies(1);
		vo.setStatus("0");
		mmap.put("vo", vo);
		return super.add(mmap);
	}
	
	@Override
	public AjaxResult addSave(ChopInfoDTO dto) throws Exception {
		AjaxResult result = super.addSave(dto);
		if (result.isSuccess()) {
			result.put("id", dto.getChopId());
		}
		return result;
	}
	
	@Override
	public String view(@PathVariable("id") Long id, ModelMap mmap) throws Exception {
		List<CxSelect> lsChopType = getChopTypeData();
		mmap.put("ctData", lsChopType);
		//
		List<IdName> sealTypes = SealTypes.getList();
		mmap.put("sealTypes", sealTypes);
		//
		List<IdName> chopStatus = ChopStatus.getList();
		mmap.put("chopStatus", chopStatus);
		//
		return super.view(id, mmap);
	}

	@Override
	public String edit(@PathVariable("id") Long id, ModelMap mmap) throws Exception {
		List<CxSelect> lsChopType = getChopTypeData();
		mmap.put("ctData", lsChopType);
		//
		List<IdName> sealTypes = SealTypes.getList();
		mmap.put("sealTypes", sealTypes);
		//
		List<IdName> chopStatus = ChopStatus.getList();
		mmap.put("chopStatus", chopStatus);
		mmap.put("curStatus", "3");
		//
		return super.edit(id, mmap);
	}

	@Override
	public String check(@PathVariable("id") Long id, ModelMap mmap) throws Exception {
		List<CxSelect> lsChopType = getChopTypeData();
		mmap.put("ctData", lsChopType);
		//
		List<IdName> sealTypes = SealTypes.getList();
		mmap.put("sealTypes", sealTypes);
		//
		List<IdName> chopStatus = ChopStatus.getList();
		mmap.put("chopStatus", chopStatus);
		//
		return super.check(id, mmap);
	}

	protected List<CxSelect> getChopTypeData() {
		List<CxSelect> cxList = new ArrayList<CxSelect>();
		{
			Map<Integer, List<ChopType>> map = chopTypeService.getGroupMapList();
			List<ChopType> lsChopType = chopTypeService.getGroupRoot();
			for (ChopType u : lsChopType) {
				CxSelect cxSelectRoot = new CxSelect(String.valueOf(u.getChopTypeId()), u.getChopTypeName());
				List<CxSelect> subList = new ArrayList<CxSelect>();
				//
				List<ChopType> lsLt = map.get(u.getChopTypeId());
				if (lsLt != null) {
					for (ChopType lt : lsLt) {
						subList.add(new CxSelect(String.valueOf(lt.getChopTypeId()), lt.getChopTypeName()));
					}
				}
				cxSelectRoot.setS(subList);
				//
				cxList.add(cxSelectRoot);
			}
		}
		return cxList;
	}

	protected List<CxSelect> getData() {
		List<CxSelect> cxList = new ArrayList<CxSelect>();
		{
			CxSelect cxSelectRoot = new CxSelect("淘宝", "taobao");
			//
			List<CxSelect> subList = new ArrayList<CxSelect>();
			subList.add(new CxSelect("天猫", "tm"));
			subList.add(new CxSelect("聚划算", "jhs"));
			//
			cxSelectRoot.setS(subList);
			//
			cxList.add(cxSelectRoot);
		}
		{
			CxSelect cxSelectRoot = new CxSelect("京东", "jd");
			//
//	        List<CxSelect> subList = new ArrayList<CxSelect>();
//	        subList.add(new CxSelect("京东超市", "jdcs"));
//	        subList.add(new CxSelect("京东生鲜", "jdsx"));
//	        //
//	        cxSelectRoot.setS(subList);
			//
			cxList.add(cxSelectRoot);
		}
		{
			CxSelect cxSelectRoot = new CxSelect("抖音", "ty");
			cxList.add(cxSelectRoot);
		}

		return cxList;
	}
	  
	//@Override
	@PostMapping("/upload")
	public String upload(@ModelAttribute FileUploadDTO dto, ModelMap model, @RequestParam("file") MultipartFile file) throws Exception {
		String msgVal = null;
		try {
		  if (dto.getId() != null) {
		      String sub = String.format("chopinfo/%d", dto.getId());
		      storeService.save(file, sub);
		      msgVal = "上传成功: " + file.getOriginalFilename();
		  } else {
		      msgVal = "上传失败: " + file.getOriginalFilename() + ". Error: " + "file id is null.";
		  }
		} catch (Exception e) {
		  msgVal = "上传失败: " + file.getOriginalFilename() + ". Error: " + e.getMessage();
		}
		String msgKey = "message";
		model.addAttribute(msgKey, msgVal);
	    if (dto.getId() != null) {
	    	return edit(dto.getId().longValue(), model);
	    } else {
	    	return edit(0L, model);
	    }
	}
	
	//@Override
//	@PostMapping("/upload/{chopId}/{item}")
//	public String uploadId(@PathVariable Integer chopId, @PathVariable Integer item, @RequestParam("file") MultipartFile file, ModelMap model) throws Exception {
//		String msgVal = null;
//		try {
//		  if (chopId != null && item != null ) {
//		      String sub = String.format("%d/%d", chopId, item);
//		      storeService.save(file, sub);
//		      msgVal = "Uploaded the file successfully: " + file.getOriginalFilename();
//		  } else {
//		      msgVal = "Could not upload the file: " + file.getOriginalFilename() + ". Error: " + "file idx is null.";
//		  }
//		} catch (Exception e) {
//		  msgVal = "Could not upload the file: " + file.getOriginalFilename() + ". Error: " + e.getMessage();
//		}
//		//String msgKey = String.format("message_%d", dto.getIdx());
//		String msgKey = "message";
//		model.addAttribute(msgKey, msgVal);
//		model.addAttribute("curIdx", item);
//	    if (chopId != null) {
//	    	return edit(chopId.longValue(), model);
//	    } else {
//	    	return edit(0L, model);
//	    }
//	}
	
	@GetMapping("/download/{chopId}/{filename:.+}")
	public ResponseEntity<Resource> download(@PathVariable Integer chopId, @PathVariable String filename) throws Exception {
		String sub = String.format("chopinfo/%d", chopId);
		Resource file = storeService.load(filename, sub);
//		HttpHeaders httpHeaders = new HttpHeaders();
//		httpHeaders.add("Content-Disposition","attachment; filename="+new String(file.getFilename().getBytes("UTF-8"),"ISO8859-1"));
      //
//		return ResponseEntity.ok()
//              .headers(httpHeaders)
//              .contentLength(file.contentLength())
//              .contentType(MediaType.parseMediaType("application/octet-stream"))
//              .body(file);		
		return ResponseEntity.ok()
	    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + new String(file.getFilename().getBytes("UTF-8"),"ISO8859-1") + "\"")
	      .contentLength(file.contentLength())
	      .contentType(MediaType.parseMediaType("application/octet-stream")).body(file);
	}

	//@Override
	@GetMapping("/delete/{chopId}/{filename:.+}")
	public String delete(@PathVariable Integer chopId, @PathVariable String filename, Model model, RedirectAttributes redirectAttributes) {
		String msgKey = "message";
	    String msgVal = null;
	    try {
	  	  String sub = String.format("chopinfo/%d", chopId);
	      boolean existed = storeService.delete(filename, sub);
	      if (existed) {
	    	  msgVal = "删除成功: " + filename;
	      } else {
	    	  msgVal = "文件不存在!";
	      }
	    } catch (Exception e) {
	       msgVal = "删除失败: " + filename + ". Error: " + e.getMessage();
	    }
	    FlashMap flashMap = RequestContextUtils.getOutputFlashMap(request);
	    flashMap.put(msgKey, msgVal);
	    return "redirect:/office/chopinfo/enroll/edit/" + chopId;
	}

}